package com.jsits.v2x.modbus.service.impl;

import com.jsits.v2x.common.dataClient.DataClient;
import com.jsits.v2x.common.dto.ControlDto;
import com.jsits.v2x.common.enums.DevicePosition;
import com.jsits.v2x.modbus.config.ModbusConfig;
import com.jsits.v2x.modbus.server.ModbusServer;
import com.jsits.v2x.modbus.service.ModebusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ModebusServiceImpl extends DataClient implements ModebusService, ApplicationListener<ApplicationReadyEvent> {
    @Autowired
    private ModbusConfig modbusConfig;

    /**
     * 获取各个显示屏需要显示的内容，并控制需要的屏幕显示
     */
    @Override
    public void updateLedScreen() {
        List<ControlDto> controlDtos = GetControlStatus(modbusConfig.getDataUrl());
        if(controlDtos != null) {
            boolean hasMan = false;
            for (ControlDto controlDto : controlDtos) {
                if(controlDto.getNumberContent() > 0) {
                    if (controlDto.getDevicePosition().equals(DevicePosition.DEVICE_POSITION_SUB_1)
                            || controlDto.getDevicePosition().equals(DevicePosition.DEVICE_POSITION_SUB_2)) {
                        hasMan = true;
                        break;
                    }
                }
            }
            ModbusServer.writeDigitalOutput(modbusConfig.getServerIp(),
                    modbusConfig.getServerPort(),
                    modbusConfig.getSlaveId(),
                    modbusConfig.getAddress(),
                    hasMan);
        }
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {

    }
}
